<!DOCTYPE html>
<html lang="zh_CN">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>PDF转图片|PDF转JPG</title>
    <meta name="keywords" content="PDF转图片、PDF转JPG">
    <meta name="description" content="在线PDF转JPG工具,使用pdf.js将PDF转为JPG图片">
    <link rel="shortcut icon" href="https://oktools.net/favicon.ico">
    <link rel="stylesheet" href="./files/style.css" type="text/css">
<body>
    <main>
        <div class="container">
            <h1>PDF转图片</h1>
            <div class="file fullwidth mt-2">
                <span class="file-cta">
                    <input id="input_file" class="file-input" type="file" accept="application/pdf"
                        onchange="loadPDF(this.files[0])">
                    <span class="file-button">选择一个PDF文件</span>
                </span>
                <span id="file_name" class="file-name"></span>
            </div>
            <div class="content-center mt-2">
                <div class="group">
                    <button class="button" onclick="prevPage()">
                        <span>上一页</span>
                    </button>
                    <button class="button" onclick="nextPage()">
                        <span>下一页</span>
                    </button>
                </div>
                <div id="out_type" class="group">
                    <button class="button primary">
                        <span>JPG</span>
                    </button>
                    <button class="button">
                        <span>PNG</span>
                    </button>
                </div>
                <button class="button primary" onclick="save()">
                    <span>保存本页</span>
                </button>
                <button class="button primary" onclick="saveAll()">
                    <span>全部保存</span>
                </button>
            </div>
            <p id="page_num"></p>
            <br>
            canvas 展示
            <br>
            <div class="content-center mt-2">
                <canvas id="preview" class="bordered"></canvas>
            </div>
            <br>
            base64  展示
            <br>
            <div class="content-center mt-2">
                <img style="border-radius: 2px;
                border: 1px solid #dbdbdb;" id="base" src=""/>
            </div>
        </div>
    </main>
    <script src="https://cdn.bootcdn.net/ajax/libs/pdf.js/3.8.162/pdf.min.js"></script>
    <script>
        pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.bootcdn.net/ajax/libs/pdf.js/3.8.162/pdf.worker.js';

        const preview = document.getElementById('preview');
        const page_num = document.getElementById('page_num');
        const out_type = document.getElementById('out_type');

        let pdfFile, pdf, pageNum, context = preview.getContext('2d');

        out_type.querySelectorAll('.button').forEach(function (btn) {
            btn.onclick = function () {
                out_type.querySelector('.primary').classList.remove('primary');
                btn.classList.add('primary');
            }
        });

        function loadPDF(file) {
            pdfFile = file;
            file_name.innerHTML = file.name;

            let reader = new FileReader();
            reader.onload = (e) => showPDF(e.target.result);
            reader.readAsDataURL(file);
        }

        function showPDF(url) {
            let loadingTask = pdfjsLib.getDocument(url);
            loadingTask.promise.then(function (doc) {
                pdf = doc;
                pageNum = 1;
                readerPage()
            }, function (reason) {
                alert(reason)
            });
        }

        function prevPage() {
            if (pageNum <= 1) {
                return;
            }
            pageNum--;
            readerPage()
        }

        function nextPage() {
            if (pageNum >= pdf.numPages) {
                return;
            }
            pageNum++;
            readerPage()
        }

        function readerPage(callback) {
            pdf.getPage(pageNum).then(function (page) {
                let scale = 1.5;
                let viewport = page.getViewport({ scale: scale });

                preview.height = viewport.height;
                preview.width = viewport.width;

                let renderContext = {
                    canvasContext: context,
                    viewport: viewport
                };
                page.render(renderContext).promise.then(()=>{
                    callback
                    let type = out_type.querySelector('.primary').innerText.toLowerCase();
                    let base64 = preview.toDataURL(type === 'png' ? 'image/png' : 'image/jpeg');
                    document.querySelector('#base').setAttribute('src',base64)
                });
            });
            page_num.innerText = `页码 : ${pageNum} / ${pdf.numPages}`;
        }

        function save() {
            let a = document.createElement('a');
            let event = new MouseEvent('click');
            let type = out_type.querySelector('.primary').innerText.toLowerCase();
            a.download = pdfFile.name + '-' + pageNum + '.' + type;
            a.href = preview.toDataURL(type === 'png' ? 'image/png' : 'image/jpeg');
            a.dispatchEvent(event)
        }

        function saveAll() {
            pageNum = 1;
            savePage()
        }

        function savePage() {
            if (pageNum > pdf.numPages) {
                alert('全部保存成功');
                return
            }

            readerPage(function () {
                save();
                pageNum++;
                savePage();
            });
        }

        var timer = null
        function timeClick() {
            clearInterval(timer)
            timer = null
            var timestamp = parseInt(document.getElementById('time').value)
            formDate(timestamp)
            timer = setInterval(()=>{
                timestamp = timestamp+1000
                formDate(timestamp)
            },1000)
        }

        function formDate(tt) {
            let time = new Date(tt);
            let y = time.getFullYear();
            let m = time.getMonth()+1+'';
            let d = time.getDate()+'';
            let h = time.getHours()+'';
            let mm = time.getMinutes()+'';
            let s = time.getSeconds()+'';
            let str =  y+'-'+m.padStart(2,'0')+'-'+d.padStart(2,'0')+' '+h.padStart(2,'0')+':'+mm.padStart(2,'0')+':'+s.padStart(2,'0');
            document.getElementById('show_time').innerHTML = str
        }

        // document.getElementById('time').value = +new Date()
        // timeClick()
    </script>
</body>

</html>